package com.gujia.concurrency.example.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量：Semaphore
 * 控制同时访问的线程个数
 * semaphore.tryAcquire() 尝试获取一个许可
 */
public class SemaphoreExample3 {

    private  static int threadCount = 20;
    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        if(semaphore.tryAcquire(1, TimeUnit.SECONDS)){
                            test(threadNum);
                            semaphore.release();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {

                    }
                }
            });
        }


        System.out.println("main finished !");
        executorService.shutdown();
    }


    private static void test(int threadNum) throws Exception{
        Thread.sleep(100);
        System.out.println("ThreadNum -> "+threadNum);
        Thread.sleep(100);
    }
}
